// const { compileString } = require("sass");

/*
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖保佑             永无BUG 
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//                  不见满街漂亮妹，哪个归得程序员？
*/
let currentCntPay = 0
let cntAllPay = 0
let QdAllPay = 0
function AllReady() {
    var mstform = Ext.getCmp('CntM4');//获取容器   
    var dgrid = Ext.getCmp('CntD4');//获取容器   
    var toolbar = Ext.getCmp('toolbar');
    var tabPanel = Ext.getCmp("tabPanel");
    addTabs(mstform, tabPanel, toolbar);
    var fb_cnt_jg = tabPanel.items.find(function (item) {
        return item.id === "fb_cnt_jg";
    });
    fb_cnt_jg.tab.onHide();
    let _timeId = 0
    var PhidDept = mstform.queryById('PhidDept');//获取字段
    var PhidPc = mstform.queryById('PhidPc');
    var PhidYsfl = mstform.queryById('PhidYsfl');
    var Iscb = mstform.queryById('Iscb');
    var user_taxrate = mstform.queryById('user_taxrate');

    var user_product_line = mstform.queryById('user_product_line');
    var user_regional_center = mstform.queryById('user_regional_center');

    toolbar.get("imp").hide()
    toolbar.get("imp_push").hide()
    toolbar.get("impinfoview").hide()
    toolbar.get("imp_push_his").hide()
    toolbar.get("cbs_balance").hide()
    toolbar.get("export").hide()
    setTitle();

    // var user_if_yfwbht=mstform.queryById("user_if_yfwbht")
    //user_if_yfwbht.setValue('1')
    // BatchBindCombox([user_if_yfwbht])
    // 去掉明细里面的合同清单名称的必输

    mstform.on('dataready', function () {
        console.log('Data ready event triggered');
        getYfYgCntPay()
    });
    /**
     * @param form 主表容器ID
     * 当前默认存储上上签合同id字段为 user_contractid ,如果不一样请传参key
     * @param key 上上签合同id字段（默认可不填）
    */
    viewBtn("CntM4")
    function viewBtn(form, key) {
        var mstform = Ext.getCmp(form)
        var toolbar = Ext.getCmp("toolbar")
        toolbar.insert(11, {
            xtype: "button",
            text: "查询合同状态",
            id: "viewBtn",
            iconCls: "icon-New",
            handler: function () {
                // 按钮点击后执行的逻辑，发送 AJAX 请求
                var phid = mstform.getItem("PhId").getValue(); // 假设 phid 存在于表单中
                //   var asrTable = mstform.getItem("asrTable").getValue(); // 假设 asrTable 存在于表单中

                // 拼接查询参数
                var url = "http://nginx.clouddev.hisense.com/sd/Signed/push/checkContractStatus"
                var user_contractid = mstform.queryById(key ? key : "user_contractid")?.getValue()
                console.log(user_contractid, phid);
                if (!user_contractid || !phid) {
                    Ext.Msg.alert("错误", "当前合同未推送至上上签 或 单据为审核！");
                    return
                }
                // 使用 GET 请求
                Ext.Ajax.request({
                    url: url,
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    jsonData: { "contractId": user_contractid },
                    success: function (response) {
                        var res = Ext.decode(response.responseText);
                        if (res.IsOk) {
                            Ext.Msg.alert("提示", res.data);
                        } else {
                            Ext.Msg.alert("错误", res.data);
                        }
                    },
                    failure: function () {
                        Ext.Msg.alert("错误", "请求失败，请稍后再试");
                    },
                });
            },
        });
    }
    dgrid.setMustInputCol("ItemName", false)
    dgrid.hideColumn('ItemName', true);
    // 获取研发预算单的所有金额和其他研发合同总额
    getCntAllPayYf()

    // 计量单位
    dgrid.setMustInputCol('Unit_EXName', false);
    dgrid.hideColumn('Unit_EXName', true);
 let cnt_type_count = 0
 if(otype == 'add'){
    window._cnt_type_timeId = setInterval(()=>{
        if(mstform.queryById("CntType").getValue()){
            mstform.queryById("user_cnt_type_dms").setValue(mstform.queryById("CntType").getValue())
            BatchBindCombox([mstform.queryById("user_cnt_type_dms")]);
            switch(Number(mstform.queryById("CntType").getValue())){
                case 8570000000000015:
                case 8570000000000016:
                case 8570000000000017:
                case 8570000000000018:
                case 8570000000000021:
                    mstform.getItem("user_cnt_model").setValue("1")
                    break
                case 8570000000000019:
                    mstform.getItem("user_cnt_model").setValue("2")
            }
            clearInterval(window._cnt_type_timeId)
        } else {
            cnt_type_count ++
        }
        // 重试20次
        if(cnt_type_count == 20){
            clearInterval(window._cnt_type_timeId)
        }
    },300)
 }
    mstform.getItem('user_ht_startdt').addListener('change', function () {//值发生变化后立即触发
        console.log(`合同开始时间`);
        setDateDay()
    })
    mstform.getItem('user_ht_enddt').addListener('change', function () {//值发生变化后立即触发
        console.log(`合同开始时间`);
        setDateDay()
    })
    mstform.getItem("PhidRecComp").addListener("change", (res) => {
        getSuppyPhone()
    })

    if (otype == 'add') {
        console.log(`测试`);
    }
    mstform.on('afterrender', function () {
        console.log('Form rendered');
    });
    mstform.on('dataready', function () {
        console.log('Data ready event triggered');
    });
    // 获取甲方单位信息
    function getSuppyPhone() {
        const phid = mstform.getItem("PhidRecComp").getValue()
        execServer("getSuppyPhone", { phid }, (res) => {
            if (res.count == 0) {
                window._saveLock = true
                return
            } else {
                const phone = JSON.parse(res.data)[0].extendObjects.phone
                mstform.queryById("user_jfdw_tel").setValue(phone)
            }
        })
    }
    function setDateDay() {
        const startdt = mstform.queryById("user_ht_startdt").getValue()
        const enddt = mstform.queryById("user_ht_enddt").getValue()
        // mstform.queryById("user_ht_month").setValue(monthsBetweenDates(startdt, enddt))
    }

    function monthsBetweenDates(date1Str, date2Str) {
        // 将字符串转换为 Date 对象
        const date1 = new Date(date1Str);
        const date2 = new Date(date2Str);

        // 确保 date2 是较晚的日期
        if (date1 > date2) {
            [date1, date2] = [date2, date1];
        }

        // 计算两个日期之间的毫秒数差值
        const timeDiff = date2.getTime() - date1.getTime();

        // 将毫秒数差值转换为天数差值，因为一天有 24 小时，每小时 60 分钟，每分钟 60 秒，每秒 1000 毫秒
        const dayDiff = Math.abs(timeDiff / (1000 * 60 * 60 * 24)) + 1; // 加 1 是为了包含起始和结束日期

        // 计算月数，用天数除以 30
        const months = dayDiff / 30;

        // 保留两位小数
        return parseFloat(months.toFixed(2));
    }

    initNum()
    // 赋值默认值
    function initNum() {
        console.log(`拿到所有行`, dgrid.store.data.items);
        const _arrRow = dgrid.store
        for (let i = 0; i < _arrRow.getCount(); i++) {
            if (_arrRow.getAt(i).get("ItemName") !== '空值') { _arrRow.getAt(i).set("ItemName", "空值") }
            console.log(`监听`, mstform.queryById("user_ht_month").getValue(), _arrRow.getAt(i).get("user_pq_month"));
            if ((Number(mstform.queryById("user_ht_month").getValue()) || 0) < (Number(_arrRow.getAt(i).get("user_pq_month")) || 0)) {
                _arrRow.getAt(i).set("user_pq_month", mstform.queryById("user_ht_month").getValue())

                console.log(`超了`);
            }
            console.log(`当前服务费`, _arrRow.getAt(i).get("user_fw_amt_month"));
            if (!_arrRow.getAt(i).get("user_fw_amt_month")) {
                _arrRow.getAt(i).set("user_fw_amt_month", 48)

            }
            _arrRow.getAt(i).set("Unit", '8570000000000371')
            _arrRow.getAt(i).set("Unit_EXName", '人')
            _arrRow.getAt(i).set("user_ry_zt", '32')
            _arrRow.getAt(i).set("user_ry_zt_name", '在职')

            // _arrRow.getAt(i).set("user_fw_amt_month", _arrRow.getAt(i).get("user_wage_standard"))

            // if(_arrRow.getAt(i).get("Unit") !== "8570000000000001"){_arrRow.getAt(i).set("Unit", "8570000000000001")}
            // if(_arrRow.getAt(i).set("Unit_EXName") !== "台"){_arrRow.getAt(i).set("Unit_EXName", "台")}
            if (["", NaN, null, undefined].indexOf(_arrRow.getAt(i).get("user_employment_type")) !== -1) {
                _arrRow.getAt(i).set("user_employment_type", "02")
            }
        }
        dgrid.getView().refresh()
    }
    getProInfo()
    // mstform.getItem('pc').addListener('change', function () {//值发生变化后立即触发

    // });
    PhidPc.addListener('change', function () {
        getProInfo()
        getYfYgCntPay()
        verifyCntPay()
        getSelfAmtTotal()
        // getPtInfoByPhid()
        getCntMInfoByPhidPc()
        getCntAllPayYf()

    });
    setTimeout(() => {
        setTitle()
    }, 500)

    function getProInfo() {
        console.log(mstform.queryById("PhidPc").getValue(), '1111111111');

        if (!PhidPc.getValue()) return
        execServer('getProjInfo', { pc: PhidPc.getValue() }, function (res) {
            if (res.count > 0) {
                var obj = JSON.parse(res.data);
                console.log('获取项目信息', obj[0]);
                PhidDept.setValue(obj[0].extendObjects.dept)
                user_product_line.setValue(obj[0].extendObjects.cpx)
                user_regional_center.setValue(obj[0].extendObjects.qyzx)
                mstform.queryById("BRPcNo").setValue(obj[0].extendObjects.pc_no)
                console.log(`测试`, obj[0].extendObjects.pc_no);
                BatchBindCombox([PhidDept])
                BatchBindCombox([user_product_line])
                BatchBindCombox([user_regional_center])
            }
        });
    }
    // getCntMInfoByPhidPc()
    function getCntMInfoByPhidPc() {
        // console.log(CntType.getValue());

        //   if (!PhidPc.getValue() || CntType.getValue() !== "8570000000000016") return;
        execServer("getCntMInfoByPhidPc", { phid_pc: PhidPc.getValue() }, function (res) {
            console.log(`getCntMInfoByPhidPc`, res);
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            console.log(`getCntMInfoByPhidPc`, _data);
            mstform.getItem("Title").setValue(`${_data.pc_name}研发外包用工合同`)


        });
    }
    //获取项目信息
    getPtInfoByPhid()
    function getPtInfoByPhid() {
        console.log(`获取项目信息`, 1);
        if (PhidPc.getValue()) {
            execServer("getPtInfoByPhid", { phid: PhidPc.getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
            });
        }
    }

    dgrid.store.on('add', function (store, records, index, eOpts) {
        console.log('增行');
        try {
            initNum()
        } catch (err) {
            console.log(`计量单位问题`, err);
        }

    })
    // execServer("getPtInfoByPhid", {phid: mstform.queryById("PhidPc").getValue()})
    dgrid.addListener('edit', function (editor, e) {//表体编辑触发
        console.log(`表体编辑`);
        var record = e.record;
        let serviceAmt = 0
        if (_timeId) {
            clearTimeout(_timeId)
        }
        try {
            _timeId = setTimeout(() => {
                sunAdd(record)
                //TODO
            }, 200)
        } catch (err) {
            console.log("累加报错");
        }
        const _data = record.store
        console.log(_data);

        for (let i = 0; i < _data.getCount(); i++) {
            // if ((Number(mstform.queryById("user_ht_month").getValue()) || 0) < (Number(_data.getAt(i).get("user_pq_month")) || 0)) {
            //     _data.getAt(i).set("user_pq_month", mstform.queryById("user_ht_month").getValue())
            //     Ext.Msg.alert("派遣月份超出合同月数！")
            //     console.log(`超了`);
            // }
            console.log(`deBug`, Number(_data.getAt(i).get("user_yg_amt_month")));
            if (!Number(_data.getAt(i).get("user_yg_amt_month"))) {
                _data.getAt(i).set("user_yg_amt_month", (Number(_data.getAt(i).get("user_wage_standard")) || 0))
            }
            _data.getAt(i).set("user_fw_amt", Number(_data.getAt(i).get("user_fw_amt_month")) * Number(_data.getAt(i).get("user_pq_month")))
            _data.getAt(i).set("user_yg_amt", Number(_data.getAt(i).get("user_yg_amt_month")) * Number(_data.getAt(i).get("user_pq_month")))
            _data.getAt(i).set("AmtVatFc", Number(_data.getAt(i).get("user_fw_amt")) + Number(_data.getAt(i).get("user_yg_amt")))
            _data.getAt(i).set("user_amt_month", Number(_data.getAt(i).get("user_fw_amt_month")) + Number(_data.getAt(i).get("user_yg_amt_month")))
            _data.getAt(i).set("user_total_amt", Number(_data.getAt(i).get("user_fw_amt")) + Number(_data.getAt(i).get("user_yg_amt")))
            serviceAmt += (Number(_data.getAt(i).get("user_fw_amt")) || 0)
        }
        mstform.queryById("user_fw_amt").setValue(serviceAmt)
        var data = dgrid.getSelectionModel().getSelection(); //获取当前选中行
        // if(){}
        console.log(`监听行`, data);
        const _arrRow = dgrid.store
        for (let i = 0; i < _arrRow.getCount(); i++) {
            const sfz = _arrRow.getAt(i).get("user_id_card")
            console.log(sfz);
            if (sfz) {
                execServer("searchSfz", { sfz: sfz }, function (res) {
                    console.log(`身份证查询结果`, res);
                    if (res.count !== 0) {
                        Ext.Msg.alert("提示", "该人员已签订合同且目前在职")
                        _arrRow.getAt(i).set("user_id_card", '')
                    }
                });
            }

        }
        const date1 = data[0].data.user_start_dt
        const date2 = data[0].data.user_end_dt
        const _date = monthsBetweenDates(date1, date2)
        console.log(data, data[0].data.user_wage_standard, '2222222222');
        // const editedField = e.field;
        // const newValue = e.value;

        // // 如果当前编辑的是 user_wage_standard 字段
        // if (editedField === 'user_wage_standard') {
        //     e.record.set("user_fw_amt_month", Number(newValue));
        // }
        // data[0].set("user_pq_month", _date)

        // data[0].set("user_fw_amt_month", Number(data[0].get("user_wage_standard")))
        dgrid.getView().refresh()
        setTimeout(() => {
            dgrid.getView().refresh()
        }, 500)

    });
    getSelfAmtTotal()
    function getSelfAmtTotal() {
        const PhidId = mstform.queryById("PhidPc").getValue()
        console.log(`调用了`);
        if (!PhidId) return
        execServer("getSelfAmtTotal", { phid_pc: PhidId }, (res) => {
            console.log(`研发费用`, res);
            if (res.count == 0) {
                window._self_amt = 0
                return
            }
            const _data = JSON.parse(res.data)[0].extendObjects
            window._self_amt = _data.amt
            mstform.queryById("user_sy_amt").setValue(window._self_amt)
            console.log(`二开费用`, window._self_amt);
        })
    }
    dgrid.getColumn('user_position_name').getEditor().on('beforetriggerclick', function (eOp, ignoreBeforeEvent) {
        dgrid.getColumn('user_position_name').getEditor().setOutFilter({ 'm.phid_pc': mstform.getItem('PhidPc').getValue() })
        var data = dgrid.getSelectionModel().getSelection();
        dgrid.getColumn('user_position_name').getEditor().addListener('helpselected', function (record) {

            console.log(`这个是检测等级`, dgrid.getSelectionModel().getSelection()[0].data, record);
            dgrid.getSelectionModel().getSelection()[0].data.user_wage_standard = record.data.u_wage_standard;
            if (!Number(dgrid.getSelectionModel().getSelection()[0].data.user_yg_amt_month)) {
                dgrid.getSelectionModel().getSelection()[0].data.user_yg_amt_month = record.data.u_wage_standard;
            }
            dgrid.getSelectionModel().getSelection()[0].data.user_qualification_grade_name = record.data.name;
            dgrid.getSelectionModel().getSelection()[0].data.user_qualification_grade = record.data.u_qualification_grade;
            // dgrid.getSelectionModel().getSelection()[0].data.user_fw_amt_month = record.data.u_wage_standard;
            dgrid.getSelectionModel().getSelection()[0].data.user_dx_phid = record.data.dphid;
            dgrid.getView().refresh();
        })
    })





    if (otype == 'add') {
        user_taxrate.setValue('0.06')
    }


    if (otype == 'add' || otype == 'edit') {
        PhidYsfl.setValue('14')
        Iscb.setValue('1')
        BatchBindCombox([PhidYsfl])

        mstform.getItem('PhidYsfl').setVisible(false);
        mstform.getItem('Iscb').setVisible(false);
        mstform.getItem('ExchRate').setVisible(false);
        mstform.getItem('CurrType').setVisible(false);
        mstform.getItem('CntType').setVisible(false);

    }
    function sunAdd(d) {
        const _data = d.store
        let _sum = 0;
        for (let i = 0; i < _data.getCount(); i++) {
            _sum += (Number(_data.getAt(i).get("AmtVatFc")) || 0)
        }
        currentCntPay = _sum
        console.log(`debug`, _sum, Number(mstform.getItem("user_taxrate").getValue()), _sum * (1 - Number(mstform.getItem("user_taxrate").getValue())));
        mstform.getItem("CntSumFc").setValue(_sum * (1 - Number(mstform.getItem("user_taxrate").getValue())))
        mstform.getItem("CntSumVatFc").setValue(_sum)
        mstform.getItem("CntTaxAmtFc").setValue(_sum - _sum * (1 - Number(mstform.getItem("user_taxrate").getValue())))
        dgrid.getView().refresh()
    }


    //计算派遣月数
    function monthsBetweenDates(date1, date2) {
        if (!date1 || !date2) return 0;
        // 获取两个日期的时间戳（以毫秒为单位）
        const timestamp1 = date1.getTime();
        const timestamp2 = date2.getTime();

        // 计算两个日期的时间差（以毫秒为单位）
        const timeDiff = timestamp2 - timestamp1;

        // 将时间差转换为月数（假设一个月平均按30天算，一天按24小时算，一小时按60分钟算，一分钟按60秒算，一秒按1000毫秒算）
        const monthsDiff = timeDiff / (30 * 24 * 60 * 60 * 1000);

        // 保留约等于5位小数
        return parseFloat(monthsDiff.toFixed(5));
    }
    // 校验合同总额是否合规/**代码未生效 */
    function verifyCntPay() {
        if (!mstform.getItem("PhidPc").getValue()) return
        execServer("getYfQdList", { phid: mstform.getItem("PhidPc").getValue() }, function (res) {
            if (res.count == 0) return
            const _payList = JSON.parse(res.data)
            console.log(`研发费用`, _payList);
            _payList.forEach(item => {
                QdAllPay += (Number(item.extendObjects.u_total_dev_amt) || 0)
            })
        })
    }


    // 所有研发合同总额
    function getCntAllPayYf() {
        const phid_pc = PhidPc.getValue()
        if(!phid_pc) return
        execServer("getCntAllPayYfByPhidPc", {phid_pc}, function (res) {
            console.log(`研发合同总额`, res.data,`\n`,);
            cntAllPay = JSON.parse(res.data)[0].extendObjects.count_pay
        })
    }
    //获取研发用工合同含税金额总和
    getYfYgCntPay()
    function getYfYgCntPay() {
        if (!mstform.getItem("PhidPc").getValue()) return
        execServer("getYfYgCntPayTotal", { phid_pc: mstform.getItem("PhidPc").getValue() }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects

            console.log(`研发合同剩余`, _data);
            window._lsz_catch_cntAmt = _data.total_amt
        })
    }
    //获取研发可用总余额
    getTowOnTotalAmt()
    function getTowOnTotalAmt() {
        if (!mstform.getItem('PhidPc').getValue()) return
        execServer("getTowOnTotalAmt", { phid_pc: mstform.getItem("PhidPc").getValue() }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            window._lsz_catch_totalAmt = (Number(_data.total_amt) || 0)
        })
    }
    function setTitle() {
        setTimeout(() => {
            const Pc_title = PhidPc.getRawValue() || "";
            mstform.queryById("Title").setValue(PhidPc.getRawValue() + '研发外包用工合同');
        }, 200);
    }
}

function beforeSaveEdit(res) {
    console.log(res);

    //判断是否超出金额范围
    if ((Number(mstform.getItem("CntSumVatFc").getValue()) || 0) > window._self_amt - window._lsz_catch_cntAmt) {
        console.log(window._self_amt, window._lsz_catch_cntAmt, window._self_amt - window._lsz_catch_cntAmt);
        Ext.Msg.alert(`当前合同金额，超出可用余额（${window._self_amt - window._lsz_catch_cntAmt}￥）`)
        return false
    }
    console.log(`保存的参数`);
    try {
        var dgrid = Ext.getCmp('CntD4');//获取容器  
        // 提示上传附件
        // Ext.Msg.alert('提示', '请上传附件');
        const data = dgrid.store
        let i = 0;
        const erroID = []
        while (i < data.getCount()) {
            try {
                if (!validateIDCard18(data.getAt(i).get("user_id_card"))) {
                    erroID.push(i)
                }
            } catch (err) {

            } finally {
                i++
            }
        }
        if (erroID.length === 0) {
            if (currentCntPay + cntAllPay > QdAllPay) {
                console.log();

                Ext.Msg.alert('警告', `研发合同总额超出研发预算费用\n,研发预算：${QdAllPay}, 其他合同：${cntAllPay}, 当前：${currentCntPay}, 原可用：${QdAllPay - cntAllPay}`);
                return false
            } else {
                return true

            }
        } else {
            let str = '第'
            for (let i = 0; i < erroID.length; i++) {
                str += `${erroID[i] + 1}、`
            }
            str += '行身份证号码格式有误！'
            Ext.Msg.alert('提示', str);
            console.log(str);
            return false
        }
    } catch (err) {
        console.log(err);
        return false
    }
}

// 身份证校验
function validateIDCard18(idCard) {
    // 身份证号的正则表达式，必须是18位（17位数字 + 1位校验码）
    const idCardRegex = /^\d{17}(\d|X|x)$/;

    // 检查身份证号格式
    if (!idCardRegex.test(idCard)) {
        return false;
    }

    // 身份证前17位数字的权重
    const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    // 校验码对应的值
    const checkCodeMap = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

    // 计算校验和
    let sum = 0;
    for (let i = 0; i < 17; i++) {
        sum += parseInt(idCard[i], 10) * weightFactors[i];
    }

    // 计算校验码
    const calculatedCheckCode = checkCodeMap[sum % 11];
    const providedCheckCode = idCard[17].toUpperCase(); // 转大写以支持小写x

    // 比较校验码
    return calculatedCheckCode === providedCheckCode;
}


//------生成主键函数(格式为日期时间毫秒+流水号)------
function generateId(sequence) {
    //获取当前时间
    const date = new Date();
    // 格式化日期为 YYMMDD
    const year = date.getFullYear().toString().slice(-2);
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    const dateStr = `${year}${month}${day}`;
    // 格式化时间为 HHMMSS
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    const seconds = date.getSeconds().toString().padStart(2, "0");
    const timeStr = `${hours}${minutes}${seconds}`;
    // 获取毫秒数，并确保是2位数
    const milliseconds = date.getMilliseconds().toString().padStart(3, "0").slice(0, 2);
    // 格式化流水号为3位
    const sequenceStr = sequence.toString().padStart(3, "0");
    // 拼接日期、时间、毫秒和流水号
    const phid = `${dateStr}${timeStr}${milliseconds}${sequenceStr}`;
    return phid;
}

function addTabs(mstform, tabPanel, toolbar) {
    //定义model
    var fb_cnt_jg_model = Ext.define("JdNextPlanmodel", {
        extend: "Ext.data.Model",
        fields: [
            {
                name: "phid",
                type: "bigInt",
                mapping: "phid",
            },
            {
                name: "mstphid",
                type: "bigInt",
                mapping: "mstphid",
            },
            {
                name: "phid_item",
                type: "bigInt",
                mapping: "phid_item",
            },
            {
                name: "phid_itemname",
                type: "string",
                mapping: "phid_itemname",
            },
            {
                name: "spec",
                type: "string",
                mapping: "spec",
            },
            {
                name: "msunit",
                type: "bigInt",
                mapping: "msunit",
            },
            {
                name: "msunit_name",
                type: "string",
                mapping: "msunit_name",
            },
            {
                name: "prc_vat",
                type: "string",
                mapping: "prc_vat",
            },
            {
                name: "bzshl",
                type: "string",
                mapping: "bzshl",
            },
            {
                name: "htshl",
                type: "string",
                mapping: "htshl",
            },
            {
                name: "remarks",
                type: "string",
                mapping: "remarks",
            },
            {
                name: "creator",
                type: "string",
                mapping: "creator",
            },
            {
                name: "editor",
                type: "string",
                mapping: "editor",
            },
            {
                name: "ng_insert_dt",
                type: "string",
                mapping: "ng_insert_dt",
            },
            {
                name: "ng_update_dt",
                type: "string",
                mapping: "ng_update_dt",
            },
        ],
    });

    //定义store
    var fb_cnt_jg_store = Ext.create("Ext.ng.JsonStore", {
        model: fb_cnt_jg_model,
    });
    //甲供物料清单 grid
    var fb_cnt_jg = Ext.create("Ext.ng.GridPanel", {
        title: "甲供材物料清单",
        id: "fb_cnt_jg",
        region: "south",
        stateful: false,
        isInit: true,
        MaxHeight: 800,
        stateId: "fb_cnt_jg", //所有单据不允许重复
        store: fb_cnt_jg_store,
        buskey: "phid", //对应的业务表主键属性
        otype: otype,
        columnLines: true,
        tbar: [
        ],

        columns: [
            Ext.create("Ext.grid.RowNumberer", { text: "序号", width: 45 }),
            {
                header: Lang.pcm3_cnt_m_phid || "主键",
                dataIndex: "phid",
                itemId: "phid",
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: Lang.pcm3_cnt_m_phid || "单据主键",
                dataIndex: "mstphid",
                itemId: "mstphid",
                width: 100,
                sortable: true,
                hidden: true,
                readOnly: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "物资名称phid",
                dataIndex: "phid_item",
                itemId: "phid_item",
                readOnly: false,
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: "规格型号",
                dataIndex: "spec",
                itemId: "spec",
                readOnly: false,
                width: 100,
                sortable: true,
                hidden: false,
            },
            {
                header: "单位id",
                dataIndex: "msunit",
                itemId: "msunit",
                readOnly: false,
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: "单价（含税）",
                dataIndex: "prc_vat",
                itemId: "prc_vat",
                readOnly: false,
                mustInput: false,
                width: 150,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngNumber",
                    allowBlank: true,
                },
                align: "right",
                mustInput: false,
                hidden: false,
                renderer: function (val) {
                    return Ext.util.Format.number(val, "000,000,000,000.000000");
                },
            },
            {
                header: "标准损耗率",
                dataIndex: "bzshl",
                itemId: "bzshl",
                readOnly: false,
                mustInput: false,
                width: 150,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngNumber",
                    allowBlank: true,
                },
                align: "right",
                mustInput: false,
                renderer: function (val) {
                    if (val === null || val === undefined || val === "") {
                        return ""; // 如果值为空，返回空字符串
                    }
                    // 将数值乘以 100，并格式化为带两位小数的百分比形式
                    return Ext.util.Format.number(val * 100, "0,000.0000") + "%";
                }
            },
            {
                header: "合同损耗率",
                dataIndex: "htshl",
                itemId: "htshl",
                readOnly: false,
                width: 150,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngNumber",
                    allowBlank: true,
                },
                align: "right",
                renderer: function (val) {
                    if (val === null || val === undefined || val === "") {
                        return ""; // 如果值为空，返回空字符串
                    }
                    // 将数值乘以 100，并格式化为带两位小数的百分比形式
                    return Ext.util.Format.number(val * 100, "0,000.0000") + "%";
                }
            },
            {
                header: "备注",
                dataIndex: "remarks",
                itemId: "remarks",
                readOnly: false,
                mustInput: false,
                width: 250,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "创建人",
                dataIndex: "creator",
                itemId: "creator",
                readOnly: false,
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: "修改人",
                dataIndex: "editor",
                itemId: "editor",
                readOnly: false,
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: '新增时间',
                dataIndex: 'ng_insert_dt',
                itemId: 'ng_insert_dt',
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: true,
                editor: {
                    xtype: 'ngDateTime',
                    allowBlank: true
                }
            },
            {
                header: '修改时间',
                dataIndex: 'ng_update_dt',
                itemId: 'ng_update_dt',
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: true,
                editor: {
                    xtype: 'ngDateTime',
                    allowBlank: true
                }
            },

        ],
        plugins: [
            Ext.create("Ext.grid.plugin.CellEditing", {
                clicksToEdit: 1,
            }),
        ],
    });
    tabPanel.add(fb_cnt_jg);
}

function getExtendData() {
    ////甲供材物资
    var fb_cnt_jg = Ext.getCmp("fb_cnt_jg");
    var extendObj1 = fb_cnt_jg.getChange(false);
    //手动建立的表名
    return {
        fb_cnt_jg: JSON.stringify(extendObj1),
    };
}